from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from app.models import User, ServiceCategory, ServiceProvider, Service, Rating, Carousel
from app import db
from functools import wraps

bp = Blueprint('admin', __name__, url_prefix='/api/admin')

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin:
            return jsonify({
                'status': 'error',
                'message': 'Admin privileges required'
            }), 403
        return f(*args, **kwargs)
    return decorated_function

# Dashboard
@bp.route('/dashboard')
@login_required
@admin_required
def dashboard():
    try:
        stats = {
            'total_users': User.query.count(),
            'total_categories': ServiceCategory.query.count(),
            'total_providers': ServiceProvider.query.count(),
            'total_services': Service.query.count(),
            'total_ratings': Rating.query.count()
        }
        return jsonify({
            'status': 'success',
            'data': stats
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# User Management
@bp.route('/users')
@login_required
@admin_required
def get_users():
    try:
        users = User.query.all()
        return jsonify({
            'status': 'success',
            'data': [{
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_admin': user.is_admin,
                'created_at': user.created_at.isoformat()
            } for user in users]
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/users', methods=['POST'])
@login_required
@admin_required
def create_user():
    try:
        data = request.get_json()
        if not all(k in data for k in ('username', 'email', 'password')):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields'
            }), 400

        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'status': 'error',
                'message': 'Username already exists'
            }), 400

        user = User(
            username=data['username'],
            email=data['email'],
            is_admin=data.get('is_admin', False)
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'User created successfully',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_admin': user.is_admin
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/users/<int:id>', methods=['PUT'])
@login_required
@admin_required
def update_user(id):
    try:
        user = User.query.get_or_404(id)
        data = request.get_json()

        if 'username' in data:
            existing_user = User.query.filter_by(username=data['username']).first()
            if existing_user and existing_user.id != id:
                return jsonify({
                    'status': 'error',
                    'message': 'Username already exists'
                }), 400
            user.username = data['username']

        if 'email' in data:
            user.email = data['email']
        if 'is_admin' in data:
            user.is_admin = data['is_admin']
        if 'password' in data:
            user.set_password(data['password'])

        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'User updated successfully',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_admin': user.is_admin
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/users/<int:id>', methods=['DELETE'])
@login_required
@admin_required
def delete_user(id):
    try:
        user = User.query.get_or_404(id)
        if user.id == current_user.id:
            return jsonify({
                'status': 'error',
                'message': 'Cannot delete your own account'
            }), 400

        db.session.delete(user)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'User deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# Service Category Management
@bp.route('/categories')
@login_required
@admin_required
def get_categories():
    try:
        categories = ServiceCategory.query.all()
        return jsonify({
            'status': 'success',
            'data': [{
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'created_at': category.created_at.isoformat()
            } for category in categories]
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/categories', methods=['POST'])
@login_required
@admin_required
def create_category():
    try:
        data = request.get_json()
        if 'name' not in data:
            return jsonify({
                'status': 'error',
                'message': 'Name is required'
            }), 400

        category = ServiceCategory(
            name=data['name'],
            description=data.get('description', '')
        )
        db.session.add(category)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'Category created successfully',
            'data': {
                'id': category.id,
                'name': category.name,
                'description': category.description
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/categories/<int:id>', methods=['PUT'])
@login_required
@admin_required
def update_category(id):
    try:
        category = ServiceCategory.query.get_or_404(id)
        data = request.get_json()

        if 'name' in data:
            category.name = data['name']
        if 'description' in data:
            category.description = data['description']

        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'Category updated successfully',
            'data': {
                'id': category.id,
                'name': category.name,
                'description': category.description
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/categories/<int:id>', methods=['DELETE'])
@login_required
@admin_required
def delete_category(id):
    try:
        category = ServiceCategory.query.get_or_404(id)
        db.session.delete(category)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'Category deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 

@bp.route('/users/admin', methods=['POST'])
@login_required
@admin_required
def create_admin():
    """创建新管理员账号"""
    try:
        data = request.get_json()
        if not all(k in data for k in ('username', 'email', 'password')):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields'
            }), 400

        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'status': 'error',
                'message': 'Username already exists'
            }), 400

        user = User(
            username=data['username'],
            email=data['email'],
            is_admin=True  # 设置为管理员
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'Admin user created successfully',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_admin': user.is_admin
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 